import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:fucius/utils/firestoreservice.dart';
import 'package:fucius/widgets/avatar.dart';
import 'package:fucius/widgets/editInfo/editinfo.dart';
import 'package:fucius/widgets/login/root_page.dart';

import 'editInfo/editjob.dart';
import 'login/authentication.dart';

class MenuItem extends StatelessWidget {
  MenuItem({Key key, this.icon, this.title, this.onPressed}) : super(key: key);

  final IconData icon;
  final String title;
  final VoidCallback onPressed;

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: onPressed,
      child: new Column(
        children: <Widget>[
          new Padding(
            padding: const EdgeInsets.only(
              left: 20.0,
              top: 12.0,
              right: 20.0,
              bottom: 10.0,
            ),
            child: new Row(
              children: [
                new Padding(
                  padding: const EdgeInsets.only(
                    right: 8.0,
                  ),
                  child: new Icon(
                    icon,
                    color: Colors.black54,
                  ),
                ),
                new Expanded(
                  child: new Text(
                    title,
                    style: new TextStyle(color: Colors.black54, fontSize: 16.0),
                  ),
                ),
                new Icon(
                  Icons.chevron_right,
                  color: Colors.grey,
                )
              ],
            ),
          ),
          new Padding(
            padding: const EdgeInsets.only(left: 20.0, right: 20.0),
            child: new Divider(),
          )
        ],
      ),
    );
  }
}

class ContactItem extends StatelessWidget {
  ContactItem({Key key, this.count, this.title, this.onPressed})
      : super(key: key);

  final String count;
  final String title;
  final VoidCallback onPressed;

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: onPressed,
      child: new Column(
        children: [
          new Padding(
            padding: const EdgeInsets.only(
              bottom: 4.0,
            ),
            child: new Text(count, style: new TextStyle(fontSize: 18.0)),
          ),
          new Text(title,
              style: new TextStyle(color: Colors.black54, fontSize: 14.0)),
        ],
      ),
    );
  }
}

class MinePage extends StatefulWidget {
  MinePage({Key key, this.auth, this.userId, this.logoutCallback})
      : super(key: key);

  final BaseAuth auth;
  final VoidCallback logoutCallback;
  final String userId;

  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage>
    with AutomaticKeepAliveClientMixin<MinePage> {
  final double _appBarHeight = 180.0;
  String _userHead = "";

  final FirebaseStorage _storage =
  FirebaseStorage(storageBucket: 'gs://fucius-a62b0.appspot.com');

  String _userId = "";
  String first_name = "";
  String middle_name = "";
  String last_name = "";
  String name = "";
  String job_title = "";
  String country = "";
  String major = "";
  String organization = "";
  String phone = "";
  String email = "";
  String personal_website = "";
  String short_bio = "";



  AuthStatus authStatus = AuthStatus.NOT_DETERMINED;
  FirestoreService fireServ = new FirestoreService();

  @override
  bool get wantKeepAlive => true;

  signOut() async {
    try {
      await widget.auth.signOut();
      widget.logoutCallback();
    } catch (e) {
      print(e);
    }
  }

  Future<dynamic> getTalent(String id) async{
    final DocumentReference ds= Firestore.instance.collection('talent').document(id);
    await ds.get().then((datasnapshot){
      print(datasnapshot.data);
      setState(() {
        name = datasnapshot.data["Name"];
      });
      first_name = datasnapshot.data["First Name"];
      middle_name = datasnapshot.data["Middle Name"];
      last_name = datasnapshot.data["Last Name"];
      job_title = datasnapshot.data['Job Title'];
      country = datasnapshot.data['Country'];
      major = datasnapshot.data['Major'];
      organization = datasnapshot.data['Organization'];
      phone = datasnapshot.data['Phone'];
      email = datasnapshot.data['Email'];
      personal_website = datasnapshot.data['Personal Website'];
      short_bio = datasnapshot.data['Short Bio'];

      return (datasnapshot.data);
    }).catchError((error) {
      print("error:"+error);
      return null;
    });
  }

  Future<dynamic> getUrl(String id) async {
    String filePath = 'images/${id}.png';
    String url = await _storage.ref().child(filePath).getDownloadURL() as String;
    setState(() {
        _userHead = url;
    });
  }

  @override
  void initState() {
    super.initState();
    widget.auth.getCurrentUser().then((user) {
      setState(() {
          _userId = user.uid;

      });
      return Future.value(_userId);
    }).then((userId){
      getTalent(userId);
      return Future.value(_userId);
    }).then((userId){
      getUrl(_userId);
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        actions: <Widget>[
          new FlatButton(
              child: new Text('Logout',
                  style: new TextStyle(fontSize: 17.0, color: Colors.white)),
              onPressed: signOut)
        ],
      ),
      backgroundColor: new Color.fromARGB(255, 242, 242, 245),
      body: new CustomScrollView(
        slivers: <Widget>[
          new SliverAppBar(
            expandedHeight: _appBarHeight,
            flexibleSpace: new FlexibleSpaceBar(
              collapseMode: CollapseMode.parallax,
              background: new Stack(
                fit: StackFit.expand,
                children: <Widget>[
                  const DecoratedBox(
                    decoration: const BoxDecoration(
                      gradient: const LinearGradient(
                        begin: const Alignment(0.0, -1.0),
                        end: const Alignment(0.0, -0.4),
                        colors: const <Color>[
                          const Color(0x00000000),
                          const Color(0x00000000)
                        ],
                      ),
                    ),
                  ),
                  new Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      new Expanded(
                        flex: 3,
                        child: new Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            new Padding(
                              padding: const EdgeInsets.only(
                                top: 30.0,
                                left: 30.0,
                                bottom: 15.0,
                              ),
                              child: new Text(
                                name,
                                style: new TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 35.0),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                          padding: EdgeInsets.only(right: 40),
                          child: new CircleAvatar(
                            radius: 60.0,
                            backgroundImage: new NetworkImage(_userHead),
                          ))
                    ],
                  ),
                ],
              ),
            ),
          ),
          new SliverList(
            delegate: new SliverChildListDelegate(
              <Widget>[
                new Container(
                  color: Colors.white,
                  margin: const EdgeInsets.only(top: 10.0),
                  child: Column(
                    children: <Widget>[
                      new MenuItem(
                          icon: Icons.face,
                          title: 'Edit Profile',
                          onPressed: () {
                            Navigator.of(context).push(MaterialPageRoute(
                                //没有传值
                                builder: (context) => EditInfoPage(userId: _userId, first_name: first_name, middle_name: middle_name, last_name: last_name, name: name, job_title: job_title, country: country, major: major, organization: organization, phone: phone, email: email,  person_website: personal_website, short_bio: short_bio,)));
                          }),
                      new MenuItem(
                          icon: Icons.print,
                          title: "I'm hiring",
                          onPressed: () {
                            Navigator.of(context).push(MaterialPageRoute(
                                //没有传值
                                builder: (context) => EditJobPage(userId: _userId,)));
                          }),
                      new MenuItem(
                        icon: Icons.security,
                        title: 'Change Avatar',
                          onPressed: () {
                            Navigator.of(context).push(MaterialPageRoute(
                              //没有传值
                                builder: (context) => ImageCapture(userId: _userId,)));
                          }
                      ),
                    ],
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
